package com.mgvlife.ddlw.service.impl;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.mgvlife.ddlw.entity.Clazz;
import com.mgvlife.ddlw.entity.Course;
import com.mgvlife.ddlw.entity.Schedule;
import com.mgvlife.ddlw.entity.SignInInfo;
import com.mgvlife.ddlw.formbean.CourseForm;
import com.mgvlife.ddlw.service.CourseService;
import com.mgvlife.ddlw.vo.Result;
import com.mgvlife.ddlw.vo.VoCourse;
import com.xinhuo.dao.DaoSupport;
import com.xinhuo.util.FileUtil;
import com.xinhuo.util.QueryResult;
import com.xinhuo.vo.JsonEasyUI;

@Service("courseService")
public class CourseServiceImpl extends DaoSupport implements CourseService {

	public Result courseAdd(CourseForm dataForm) throws Exception {
		String courseName = dataForm.getName();
		boolean isCourseNameExist = this.checkCourseNameExist(courseName);
		if (isCourseNameExist) {
			return new Result("error", "课程名已存在");
		}
		Course course = new Course();
		course.setId(UUID.randomUUID().toString());
		course.setName(courseName);
		course.setSchedules(new ArrayList<Schedule>());
		this.save(course);
		return Result.success();
	}

	public Result courseUpdate(CourseForm dataForm) throws Exception {
		String courseId = dataForm.getId();
		Course course = null;
		if (courseId == null || courseId.trim().equals("")) {
			return new Result("error", "无此课程");
		} else {
			course = this.findById(Course.class, courseId);
		}
		String courseName = dataForm.getName();
		if (!courseName.equals(course.getName())) {
			boolean isCourseNameExist = this.checkCourseNameExist(courseName);
			if (isCourseNameExist) {
				return new Result("error", "课程名已存在");
			}
			course.setName(courseName);
		}
		this.update(course);
		return Result.success();
	}

	public JsonEasyUI<VoCourse> getData(CourseForm dataForm) {
		JsonEasyUI<VoCourse> result = new JsonEasyUI<VoCourse>();
		QueryResult<Course> qr = this.getScrollData(Course.class, null, null,
				dataForm.getSearchTitle(), dataForm.getSearch(),
				dataForm.getPage(), dataForm.getRows(), dataForm.getSort(),
				dataForm.getOrder());
		result.setTotal(qr.getTotalrecord());
		List<VoCourse> course_l = new ArrayList<VoCourse>();
		for (Course course : qr.getResultList()) {
			course_l.add(new VoCourse(course));
		}
		result.setRows(course_l);
		return result;
	}

	public JsonEasyUI<VoCourse> getAllData() {
		JsonEasyUI<VoCourse> result = new JsonEasyUI<VoCourse>();
		LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
		orderBy.put("name", "asc");
		List<Course> courses = this.findAll(Course.class, null, null, orderBy);
		List<VoCourse> course_l = new ArrayList<VoCourse>();
		for (Course course : courses) {
			course_l.add(new VoCourse(course));
		}
		result.setRows(course_l);
		result.setTotal((long) courses.size());
		return result;
	}
	
	public Result courseDelete(CourseForm dataForm) throws Exception {
		String filePath = ServletActionContext.getServletContext().getRealPath(
				"/data/");
		String courseId = dataForm.getId();
		if (courseId != null && courseId.length() > 0) {
			String whereSQL = "";
			String[] ids = courseId.split(";");
			boolean isFirst = true;
			for (int i = 0; i < ids.length; i++) {
				if (isFirst) {
					whereSQL = "id in (?";
					isFirst = false;
				} else {
					whereSQL += ", ?";
				}
			}
			whereSQL += ")";
			List<Course> courses = this.findAll(Course.class, whereSQL, ids);
			for (Course course : courses) {
				for (Schedule schedule : course.getSchedules()) {
					for (Clazz clazz : schedule.getClazzs()) {
						clazz.getSchedules().remove(schedule);
					}
					for (SignInInfo signInInfo : schedule.getSignInInfos()) {
						signInInfo.getStudent().getSignInInfos().remove(signInInfo);
					}
					FileUtil.deleteFile(filePath + "\\" + schedule.getSignInFile().getFileName());
				}
				this.delete(course);
			}
		} else {
			return new Result("error", "课程不存在");
		}
		return Result.success();
	}

	public boolean checkCourseNameExist(String courseName) {
		String whereSQL = "name=?";
		Object[] whereParams = { courseName };
		long count = this.getDataCount(Course.class, whereSQL, whereParams);
		return count > 0;
	}

}
